/*
 * Copyright (C) 2018 guomw.Inc. All rights reserved.
 * 项目名称： report-manage
 * 文件名称： SignatureUtils.java
 * Date：18-11-5 上午10:54
 * Author: guomw
 */

package com.guomw.report.common.utils;

import com.guomw.report.common.config.Constant;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author guomw
 * @date 2018/9/11
 */
public class SignatureUtils {
    private static Log log = LogFactory.getLog(SignatureUtils.class);
    /**
     * 获取签名
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getSign(HttpServletRequest request) throws UnsupportedEncodingException {
        Map<String, String> resultMap = new TreeMap<>();

        Map<String, String[]> map = request.getParameterMap();
        map.forEach((key, value) -> {
            if (!Constant.SIGN_KEY.equals(key)) {
                if (value != null && value.length > 0) {
                    resultMap.put(key.toLowerCase(), value[0]);
                }
            }
        });
        String strSign = buildSignIgnoreEmpty(resultMap, null, Constant.SECRET_KEY);
        log.debug("sign:" + strSign);
        return strSign.toUpperCase();
    }


    /**
     * 创建一个sign签名
     * 忽略值为空的
     *
     * @param params 代签名参数，key排序的map
     * @param prefix 签名前缀
     * @param suffix 签名后缀
     * @return 返回鉴权信息字符串
     */
    @SuppressWarnings("unchecked")
    private static String buildSignIgnoreEmpty(Map<String, String> params, String prefix, String suffix) throws UnsupportedEncodingException {
        if (prefix == null) {
            prefix = "";
        }
        if (suffix == null) {
            suffix = "";
        }
        List arrayList = new ArrayList(params.entrySet());
        Collections.sort(
                arrayList, (arg1, arg2) -> {
                    Map.Entry obj1 = (Map.Entry) arg1;
                    Map.Entry obj2 = (Map.Entry) arg2;
                    return (obj1.getKey()).toString().toLowerCase().compareTo(
                            obj2.getKey().toString().toLowerCase()
                    );
                }
        );
        StringBuilder stringBuilder = new StringBuilder(prefix);
        for (Object anArrayList : arrayList) {
            Map.Entry entry = (Map.Entry) anArrayList;
            if (StringUtils.isEmpty(entry.getValue().toString())) {
                continue;
            }
            String key = (String) entry.getKey();
            stringBuilder.append(key.toLowerCase());
            stringBuilder.append(entry.getValue());
        }
        stringBuilder.append(suffix);
        log.debug("before sign:" + stringBuilder.toString());
        return DigestUtils.md5DigestAsHex(stringBuilder.toString().getBytes("UTF-8"));
    }
}
